package com.gr.experimental.model.impl.distr;

import com.gr.experimental.model.impl.distr.operations.Expression;
import com.gr.experimental.model.impl.distr.operations.PerformActionException;
import com.gr.experimental.utils.validation.ValidationException;
import com.gr.experimental.utils.validation.ValidationUtils;

public class ConditionalAction implements Action {

	Expression condition;
	
	Action ifAction;
	Action elseAction;

	public ConditionalAction(Expression condition, Action ifAction) {
		this(condition, ifAction, null);
	}
	
	/**
	 * @param condition the condition to satisfy
	 * @param ifAction action fired when the condition is satisfied
	 * @param elseAction action fired when the condition is not satisfied
	 */
	public ConditionalAction(Expression condition, Action ifAction, Action elseAction) {
		try {
			ValidationUtils.assertClassAssignable("Condition", Boolean.class, condition.getValueType());
			this.condition = condition;
			this.ifAction = ifAction;
			this.elseAction = elseAction;
		} catch (ValidationException e) {
			throw new IllegalArgumentException(e);
		}
	}
	
	@Override
	public void perform(Context context) throws PerformActionException {
		
		try {
			if ((Boolean)condition.getValue(context)) {
				ifAction.perform(context);
			} else if (elseAction != null) {
				elseAction.perform(context);
			}
		} catch(Exception e) {
			throw new PerformActionException("Error performing action", e);
		}

	}
	
}
